﻿using DevDemo.Entity;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace DevDemo.UploadFile
{
    public partial class UploadFile : DevExpress.XtraEditors.XtraForm
    {
        public static List<FILEMODEL> fileModels = new List<FILEMODEL>();

        public static List<FILEMODEL> GetfileModels = new List<FILEMODEL>();

        public static List<ProjectModel> projectModels = new List<ProjectModel>();

        public static ProjectModel CheckProjectModel = new ProjectModel();

        public UploadFile()
        {
            InitializeComponent();

            this.WindowState = FormWindowState.Maximized;
        }

        /// <summary>
        /// Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UploadFile_Load(object sender, EventArgs e)
        {
            projectModels = new List<ProjectModel>();

            LoadProjects();
        }

        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Choose_File_Click(object sender, EventArgs e)
        {
            Stream mystream;

            OpenFileDialog openfiledialog1 = new OpenFileDialog();

            openfiledialog1.Multiselect = true;//允许同时选择多个文件 

            openfiledialog1.InitialDirectory = "c:\\Lib\\";

            openfiledialog1.Filter = "All files(*.*)|*.*";

            openfiledialog1.FilterIndex = 2;

            openfiledialog1.RestoreDirectory = true;

            if (openfiledialog1.ShowDialog() == DialogResult.OK)
            {
                if ((mystream = openfiledialog1.OpenFile()) != null)
                {
                    tb_File.Text = "";

                    for (int fi = 0; fi < openfiledialog1.FileNames.Length; fi++)
                    {
                        tb_File.Text += openfiledialog1.FileNames[fi].ToString() + " ";
                    }

                    //checkedListBoxControl1.DataSource = openfiledialog1.FileNames;

                    mystream.Close();
                }
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Upload_File_Click(object sender, EventArgs e)
        {
            FindOrigin(treeList_Data);

            if (GetfileModels.Count > 0)
            {
                btn_Upload_File.Text = "上传文件（" + GetfileModels.Count + "）";

                /*调用上传*/
                string filePath = GetfileModels[0].FILESNAME + "\\" + GetfileModels[0].NAME;
                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read);
                // Read the Data into the Byte Array
                byte[] fileByte = new byte[fs.Length];
                fs.Read(fileByte, 0, (int)fs.Length);

                IWSUpload.WebServiceUploadSoapClient
                    a = new IWSUpload.WebServiceUploadSoapClient();

                int indexof = filePath.LastIndexOf(".") + 1;
                string fileExt = filePath.Substring(indexof, filePath.Length - indexof);
                string filename = a.Upload(fileByte, fileExt);
            }
        }

        /// <summary>
        /// 选择文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_ChooseFiles_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();

            dialog.Description = "请选择文件路径";

            dialog.SelectedPath = "E:\\电影\\漫威宇宙";

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string foldPath = dialog.SelectedPath;

                tb_File.Text = foldPath;

                fileModels.Clear();

                //根节点
                fileModels.Add(new FILEMODEL { PID = "", ID = "0", NAME = foldPath, FILESNAME = "", EXTNAME = "", FILEDATE = "" });

                GetFolder(foldPath, "*", "0");

                List<FILEMODEL> obj = fileModels;

                treeList_Data.KeyFieldName = "ID";

                treeList_Data.ParentFieldName = "PID";

                treeList_Data.DataSource = null;

                treeList_Data.DataSource = obj;
            }
        }

        #region 操作文件

        /// <summary>
        /// 遍历文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="extName"></param>
        /// <param name="Pid"></param>
        private static void GetFolder(string path, string extName, string Pid)
        {
            string[] files = Directory.GetFiles(path); //文件列表

            string[] dir = Directory.GetDirectories(path); //文件夹列表

            DirectoryInfo fdir = new DirectoryInfo(path);

            FileInfo[] file = fdir.GetFiles();

            foreach (FileInfo f in file)
            {
                string guid = Guid.NewGuid().ToString();

                if (extName != "*")
                {
                    if (extName.ToLower().IndexOf(f.Extension.ToLower()) >= 0)
                    {
                        fileModels.Add(new FILEMODEL { PID = Pid, ID = guid, NAME = f.Name, FILESNAME = f.DirectoryName, EXTNAME = f.Extension, FILEDATE = f.LastWriteTime.ToString("yyyy-MM-dd hh:mm:ss") });
                    }
                }
                else
                {
                    fileModels.Add(new FILEMODEL { PID = Pid, ID = guid, NAME = f.Name, FILESNAME = f.DirectoryName, EXTNAME = f.Extension, FILEDATE = f.LastWriteTime.ToString("yyyy-MM-dd hh:mm:ss") });
                }
            }

            foreach (string fold in dir)
            {
                string[] str_arr = fold.Split('\\');

                string folderName = str_arr[str_arr.Length - 1];

                string guid = Guid.NewGuid().ToString();

                fileModels.Add(new FILEMODEL { PID = Pid, ID = guid, NAME = folderName, FILESNAME = fold, EXTNAME = "", FILEDATE = "" });

                GetFolder(fold, extName, guid);
            }
        }

        /// <summary>
        /// 获取选择
        /// </summary>
        /// <param name="nodes"></param>
        private void GetCheckedNodes(TreeListNodes nodes)
        {
            foreach (TreeListNode item in nodes)
            {
                if (item.Checked)
                {
                    var checkedMat = (FILEMODEL)treeList_Data.GetDataRecordByNode(item);
                    fileModels.Add(checkedMat);
                }
                if (item.Nodes != null && item.Nodes.Count != 0)
                {
                    GetCheckedNodes(item.Nodes);
                }
            }
        }

        /// <summary>
        /// 获取选择状态的数据主键ID集合
        /// </summary>
        /// <param name="parentNode">父级节点</param>
        private void GetCheckedKeyID(TreeListNode parentNode)
        {
            if (parentNode.Nodes.Count == 0)
            {
                return;//递归终止
            }

            foreach (TreeListNode node in parentNode.Nodes)
            {
                if (node.CheckState == CheckState.Checked)
                {
                    FILEMODEL drv = treeList_Data.GetDataRecordByNode(node) as FILEMODEL;

                    //if (drv != null && !string.IsNullOrEmpty(drv.EXTNAME))
                    //{
                    GetfileModels.Add(drv);
                    //}
                }

                GetCheckedKeyID(node);
            }
        }

        /// <summary>
        /// 获取选中的节点
        /// </summary>
        /// <param name="tree"></param>
        private void FindOrigin(TreeList tree)
        {
            GetfileModels.Clear();

            if (tree.Nodes.Count > 0)
            {
                foreach (TreeListNode root in tree.Nodes)
                {
                    GetCheckedKeyID(root);
                }
            }
        }

        #endregion

        #region 节点选中前事件

        private void treeList_Data_BeforeCheckNode(object sender, DevExpress.XtraTreeList.CheckNodeEventArgs e)
        {
            if (e.PrevState == CheckState.Checked)
            {
                e.State = CheckState.Unchecked;
            }
            else
            {
                e.State = CheckState.Checked;
            }
        }

        #endregion

        #region 节点选中后事件

        private void treeList_Data_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
        {
            SetCheckedChildNodes(e.Node, e.Node.CheckState);
            SetCheckedParentNodes(e.Node, e.Node.CheckState);
        }

        #endregion

        #region 设置子节点状态
        private void SetCheckedChildNodes(DevExpress.XtraTreeList.Nodes.TreeListNode node, CheckState check)
        {
            for (int i = 0; i < node.Nodes.Count; i++)
            {
                node.Nodes[i].CheckState = check;
                SetCheckedChildNodes(node.Nodes[i], check);
            }
        }
        #endregion

        #region 设置父节点状态
        private void SetCheckedParentNodes(DevExpress.XtraTreeList.Nodes.TreeListNode node, CheckState check)
        {
            if (node.ParentNode != null)
            {
                bool b = false;
                CheckState state;
                for (int i = 0; i < node.ParentNode.Nodes.Count; i++)
                {
                    state = (CheckState)node.ParentNode.Nodes[i].CheckState;
                    if (!check.Equals(state))
                    {
                        b = !b;
                        break;
                    }
                }
                if (b)
                {
                    node.ParentNode.CheckState = CheckState.Indeterminate;
                }
                else
                {
                    node.ParentNode.CheckState = check;
                }
                SetCheckedParentNodes(node.ParentNode, check);
            }
        }
        #endregion

        /// <summary>
        /// 新建项目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BBI_AddPrpject_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Upload_ProjectAdd projectAdd = new Upload_ProjectAdd();

            projectAdd.CheckedProject = null;

            if (projectAdd.ShowDialog() == DialogResult.OK)
            {
                List<ProjectModel> obj = projectAdd.projects;

                if (obj != null)
                {
                    foreach (var item in obj)
                    {
                        projectModels.Add(item);
                    }

                    treeList_Project.KeyFieldName = "PROJECTID";

                    treeList_Project.ParentFieldName = "PROJECTPID";

                    treeList_Project.DataSource = null;

                    treeList_Project.DataSource = projectModels;

                    #region 保存到XML

                    string strXml = Serializer(typeof(List<ProjectModel>), projectModels);

                    string tempFilePath = Environment.CurrentDirectory;

                    WriteMessage(tempFilePath + "\\PROJECTS.xml", strXml);

                    #endregion
                }
            }
        }

        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BBI_ChooseFile_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Btn_ChooseFiles_Click(null, null);
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BBI_UploadFile_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            btn_Upload_File_Click(null, null);
        }

        /// <summary>
        /// 添加版本
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BBI_AddEdition_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Upload_ProjectAdd projectAdd = new Upload_ProjectAdd();

            projectAdd.CheckedProject = CheckProjectModel;

            projectAdd.str_state = "AddSonItem";

            if (projectAdd.ShowDialog() == DialogResult.OK)
            {
                List<ProjectModel> obj = projectAdd.projects;

                if (obj != null)
                {
                    foreach (var item in obj)
                    {
                        projectModels.Add(item);
                    }

                    treeList_Project.DataSource = null;

                    treeList_Project.DataSource = projectModels;
                }
            }
        }

        /// <summary>
        /// 树表鼠标事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeList_Project_MouseUp(object sender, MouseEventArgs e)
        {
            TreeListHitInfo hitInfo = treeList_Project.CalcHitInfo(new Point(e.X, e.Y));

            TreeListNode node = hitInfo.Node;

            if (node != null)
            {
                treeList_Project.FocusedNode = node;

                string Project_ID = treeList_Project.FocusedNode["PROJECTID"].ToString();

                CheckProjectModel = projectModels.Where(b => b.PROJECTID == Project_ID).ToList()[0];

                //右键
                if (e.Button == MouseButtons.Right)
                {
                    if (CheckProjectModel.PROJECT_TYPE == 0)
                    {
                        Btn_SaveProjectFiles.Enabled = true;

                        popupMenu1.ShowPopup(MousePosition);
                    }
                    else
                    {
                        Btn_SaveProjectFiles.Enabled = false;

                        popupMenu2.ShowPopup(MousePosition);
                    }
                }

                //左键
                if (e.Button == MouseButtons.Left)
                {
                    if (CheckProjectModel.PROJECT_TYPE == 0)
                    {
                        Btn_SaveProjectFiles.Enabled = true;
                    }
                    else
                    {
                        Btn_SaveProjectFiles.Enabled = false;
                    }
                }
            }
        }

        /// <summary>
        /// 项目信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BBI_ProjectInfo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Upload_ProjectAdd projectAdd = new Upload_ProjectAdd();

            projectAdd.CheckedProject = CheckProjectModel;

            projectAdd.str_state = "GetProjectInfo";

            if (projectAdd.ShowDialog() == DialogResult.OK)
            {
                List<ProjectModel> obj = projectAdd.projects;

                if (obj != null)
                {
                    projectModels.Remove(CheckProjectModel);

                    foreach (var item in obj)
                    {
                        projectModels.Add(item);
                    }

                    treeList_Project.DataSource = null;

                    treeList_Project.DataSource = projectModels;
                }
            }
        }

        /// <summary>
        /// 产品文件目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BBI_ProductFiles_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string tempFilePath = Environment.CurrentDirectory + "\\PROJECTFILES\\" + CheckProjectModel.PROJECTID + ".xml";

            if (File.Exists(tempFilePath))
            {
                string readxml = File.ReadAllText(tempFilePath);

                List<FILEMODEL> obj = Deserialize(typeof(List<FILEMODEL>), readxml) as List<FILEMODEL>;

                //根节点
                obj.Add(new FILEMODEL { PID = "", ID = "0", NAME = "ROOT", FILESNAME = "", EXTNAME = "", FILEDATE = "" });

                treeList_Data.KeyFieldName = "ID";

                treeList_Data.ParentFieldName = "PID";

                treeList_Data.DataSource = null;

                treeList_Data.DataSource = obj;
            }
            else
            {
                Btn_ChooseFiles_Click(null, null);
            }
        }

        /// <summary>
        /// 保存项目结构
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_SaveProjectFiles_Click(object sender, EventArgs e)
        {
            FindOrigin(treeList_Data);

            string strXml = Serializer(typeof(List<FILEMODEL>), GetfileModels);

            string tempFilePath = Environment.CurrentDirectory + "\\PROJECTFILES\\";

            if (!File.Exists(tempFilePath))
            {
                Directory.CreateDirectory(tempFilePath);
            }

            WriteMessage(tempFilePath + "\\" + CheckProjectModel.PROJECTID + ".xml", strXml);
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string Serializer(Type type, object obj)
        {
            MemoryStream Stream = new MemoryStream();

            XmlSerializer xml = new XmlSerializer(type);

            try
            {
                xml.Serialize(Stream, obj);//序列化对象
            }
            catch (InvalidOperationException)
            {
                throw;
            }

            Stream.Position = 0;

            StreamReader sr = new StreamReader(Stream);

            string str = sr.ReadToEnd();

            sr.Dispose();

            Stream.Dispose();

            return str;
        }

        #region 反序列化

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="xml">XML字符串</param>
        /// <returns></returns>
        public static object Deserialize(Type type, string xml)
        {
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer xmldes = new XmlSerializer(type);

                    return xmldes.Deserialize(sr);
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type"></param>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static object Deserialize(Type type, Stream stream)
        {
            XmlSerializer xmldes = new XmlSerializer(type);

            return xmldes.Deserialize(stream);
        }

        #endregion

        /// <summary>
        /// 输出指定信息到文本文件
        /// </summary>
        /// <param name="path">文本文件路径</param>
        /// <param name="msg">输出信息</param>
        public static void WriteMessage(string path, string msg)
        {
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.BaseStream.Seek(0, SeekOrigin.End);
                    //sw.WriteLine("{0}\n{1}", msg, DateTime.Now);
                    sw.WriteLine("{0}", msg);
                    sw.Flush();
                }
            }
        }

        /// <summary>
        /// 加载项目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BBI_LoadProject_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            LoadProjects();
        }

        /// <summary>
        /// 加载项目信息
        /// </summary>
        private void LoadProjects()
        {
            string tempFilePath = Environment.CurrentDirectory + "\\PROJECTS.xml";

            if (File.Exists(tempFilePath))
            {
                string readxml = File.ReadAllText(tempFilePath);

                projectModels = Deserialize(typeof(List<ProjectModel>), readxml) as List<ProjectModel>;

                treeList_Project.KeyFieldName = "PROJECTID";

                treeList_Project.ParentFieldName = "PROJECTPID";

                treeList_Project.DataSource = null;

                treeList_Project.DataSource = projectModels;
            }
        }

        /// <summary>
        /// 指定版本设置文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BBI_EditionFiles_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Btn_Choose_File_Click(null, null);
        }
    }
}